package com.witframework.plugin.jbossrules.support;

import java.io.InputStream;
import java.io.StringReader;

import org.apache.log4j.Logger;
import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.compiler.PackageBuilder;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.springframework.core.io.Resource;

import com.witframework.plugin.jbossrules.RulesEngineException;


public class ExcelRuleBaseLoader extends AbstractFileRuleBaseLoader {
	private static Logger logger = Logger.getLogger(ExcelRuleBaseLoader.class);
	public RuleBase buildRuleBase() throws RulesEngineException {
		RuleBase ruleBase = RuleBaseFactory.newRuleBase();
		SpreadsheetCompiler converter = new SpreadsheetCompiler();
		try {
			Resource[] resources = getRuleFiles(ruleFiles);
			for(int i=0;i<resources.length;i++){
				Resource resource=resources[i];
				PackageBuilder builder = new PackageBuilder();
				InputStream source=resource.getInputStream();
				String drl = converter.compile(source,
						InputType.XLS);
				builder.addPackageFromDrl(new StringReader(drl));
				org.drools.rule.Package pkg = builder.getPackage();
				ruleBase.addPackage(pkg);
				source.close();
			}
			return ruleBase;
		} catch (Exception e) {
			logger.error("Exception occurred while load rules.",e);
			throw new RulesEngineException("Could not load rules", e);
		}
	}
}
